package com.example.studyktdemo.ui.fragment

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.studyktdemo.R
import com.example.studyktdemo.adapter.HomeAdapter
import com.example.studyktdemo.adapter.HomeBannerAdapter
import com.example.studyktdemo.base.BaseFragment
import com.example.studyktdemo.databinding.FragmentHomeBinding
import com.example.studyktdemo.bean.HomeBean
import com.example.studyktdemo.constants.Constants
import com.example.studyktdemo.uitls.ResourceUtils
import com.example.studyktdemo.viewmodel.HomeFragmentViewModel
import com.youth.banner.indicator.CircleIndicator

class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val TAG: String = "HomeFragment"

    //保存首页数据
    private var mHomeBannerData: HomeBean? = null

    //判断是不是第一次加载首页数据
    private var isFirstLoad: Boolean = true

    //加载成功的次数
    private var loadCount = 0
    private lateinit var viewModel: HomeFragmentViewModel
    private lateinit var homeAdapter: HomeAdapter
    private lateinit var bannerAdapter: HomeBannerAdapter

    //首次进入和刷新下一页的链接
    private var nextPageUrl: String? = null

    private val linearLayoutManager by lazy {
        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        )[HomeFragmentViewModel::class.java]
        initListener()
    }

    override fun initListener() {
        //加载更多
        binding.refreshHome.setOnLoadmoreListener {
            if (loadCount >= Constants.HOME_MAX_REFRESH) {
                Toast.makeText(activity, "", Toast.LENGTH_SHORT).show()
                binding.refreshHome.finishLoadmore()
                return@setOnLoadmoreListener
            }
            nextPageUrl = nextPageUrl?.replace("http", "https")
            nextPageUrl?.let { viewModel.loadMore(it) }
        }
    }

    override fun initData() {
        viewModel.queryBannerData()
    }

    override fun initView() {
        //禁止下拉刷新
        binding.refreshHome.isEnableRefresh = false
        homeAdapter = HomeAdapter()
        binding.homeContainerRv.adapter = homeAdapter
        binding.homeContainerRv.layoutManager = linearLayoutManager
        binding.homeContainerRv.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.top = 20
            }
        })

        //初始化Banner
        binding.homeBanner.setIndicator(CircleIndicator(context), true)
            .setIndicatorSelectedColor(ResourceUtils.getColor(R.color.color_white))
            .setIndicatorNormalColor(ResourceUtils.getColor(R.color.color_title_bg))
            .setIndicatorWidth(15, 15)
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_home
    }

    override fun initObserver() {
        //查询首页Banner数据
        viewModel.getHomeMutableLiveData()
            ?.observe(viewLifecycleOwner, { homeData ->
                if (homeData != null) {
                    binding.homeStatus.showContent()
                    this.mHomeBannerData = homeData
                    nextPageUrl = homeData.nextPageUrl.replace("http", "https")
                    viewModel.loadMore(nextPageUrl!!)
                    //去掉第一个
                    val list = ArrayList<HomeBean.Issue.Item>()
                    for (i in 0 until mHomeBannerData!!.issueList[0].itemList.size) {
                        if (mHomeBannerData!!.issueList[0].itemList[i].type == "video") {
                            list.add(mHomeBannerData!!.issueList[0].itemList[i])
                        }
                    }
                    bannerAdapter = HomeBannerAdapter(list)
                    binding.homeBanner.setAdapter(bannerAdapter)
                } else {
                    binding.homeStatus.showEmpty()
                }
            })

        //加载更多
        viewModel.getNextPageMutableLiveData()?.observe(viewLifecycleOwner, { loadMoreData ->
            if (loadMoreData != null) {
                binding.refreshHome.finishLoadmore()
                nextPageUrl = loadMoreData.nextPageUrl
                val data = loadMoreData.issueList[0].itemList
                Log.d(TAG, "data---> $data")
                if (isFirstLoad) {
                    homeAdapter.setData(data)
                    isFirstLoad = false
                } else {
                    loadCount++
                    homeAdapter.addHomeData(data)
                }
            }
        })
    }
}